package com.xxx.meter.model.http;

import android.annotation.SuppressLint;
import android.app.Activity;

import com.google.gson.Gson;
import com.jakewharton.retrofit2.adapter.rxjava2.HttpException;
import com.xxx.meter.R;
import com.xxx.meter.app.App;
import com.xxx.meter.base.BaseActivity;
import com.xxx.meter.model.http.bean.base.BaseBean;
import com.xxx.meter.model.http.utils.ApiCode;
import com.xxx.meter.model.log.LogConst;
import com.xxx.meter.model.log.LogUtil;
import com.xxx.meter.model.utils.SystemUtil;
import com.xxx.meter.model.utils.ToastUtil;

import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import io.reactivex.Observer;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

public abstract class ApiCallback<T> implements Observer<BaseBean<T>> {

    //弱引用对象
    private WeakReference<BaseActivity> activity;  //绑定上下文
    private CompositeDisposable compositeDisposable = new CompositeDisposable();    //防止内存泄漏
    private boolean isOpenLoading;  //是否弹出加载

    //必须使用封装的上下文Activity 否则发起网络请求会报错
    protected ApiCallback(BaseActivity activity, boolean isOpenLoading) {
        if (activity == null) {
            ToastUtil.showToast(App.getContext().getString(R.string.error_http_not_ui));
            return;
        }
        this.isOpenLoading = isOpenLoading;
        this.activity = new WeakReference<>(activity);
    }

    //必须重写 请求成功的方法
    public abstract void onSuccess(T bean);

    //等待重写 请求失败的方法
    public abstract void onError(int errorCode, String errorMessage);


    @SuppressLint("NewApi")
    @Override
    public void onSubscribe(Disposable d) {
        if (activity != null) {
            BaseActivity activity = this.activity.get();
            if (activity != null && !activity.isDestroyed()) {
                if (!SystemUtil.isNetworkAvailable(activity)) {
                    //开始请求
                    if (isOpenLoading) {
                        activity.showLoading();
                    }
                    compositeDisposable.add(d);
                } else {
                    //如果没有网络 就停止请求 并且弹出异常
                    onError(ApiCode.SERVICE_ERROR_CODE, activity.getResources().getText(R.string.error_http_net_work_exception).toString());
                    onComplete();
                }
            }
        }
    }

    @SuppressLint("NewApi")
    @Override
    public void onNext(BaseBean<T> bean) {
        if (activity != null) {
            Activity activity = this.activity.get();
            if (activity != null && !activity.isDestroyed()) {
                if (bean != null) {
                    int code = bean.getCode();
                    //使用code值做判断
                    if (code == ApiCode.RESPONSE_CODE) {
                        T data = bean.getData();
                        onSuccess(data);
                    } else {
                        //回调错误信息
                        String errorMessage = bean.getMessage() == null ? activity.getResources().getText(R.string.error_http_service_exception).toString() : bean.getMessage();
                        onError(code, errorMessage);
                    }
                } else {
                    //解析失败
                    String errorMessage = activity.getResources().getText(R.string.error_http_json_exception).toString();
                    onError(ApiCode.SERVICE_ERROR_CODE, errorMessage);
                }
            }
        }
    }

    @SuppressLint("NewApi")
    @Override
    public void onError(Throwable e) {
        if (activity != null) {
            Activity activity = this.activity.get();
            if (activity != null && !activity.isDestroyed()) {
                String errorMessage;
                int code = ApiCode.SERVICE_ERROR_CODE;
                if (e instanceof com.jakewharton.retrofit2.adapter.rxjava2.HttpException) {
                    ResponseBody errorBody = ((HttpException) e).response().errorBody();
                    if (errorBody != null) {
                        try {
                            String string = errorBody.string();
                            BaseBean bean = new Gson().fromJson(string, BaseBean.class);
                            code = bean.getCode();
                            errorMessage = bean.getMessage();
                        } catch (Exception e1) {
                            errorMessage = activity.getResources().getText(R.string.error_http_json_exception).toString();
                        }
                    } else {
                        errorMessage = activity.getResources().getText(R.string.error_http_json_exception).toString();
                    }
                } else if (e instanceof UnknownHostException) {    //首先判断地址是否正确
                    errorMessage = activity.getResources().getText(R.string.error_http_url_exception).toString();
                } else if (e instanceof SocketTimeoutException || e instanceof ConnectException) {  //再判断是否是链接超时
                    errorMessage = activity.getResources().getText(R.string.error_http_time_out_exception).toString();
                } else {
                    errorMessage = e == null ? activity.getResources().getText(R.string.error_http_not).toString() : e.getMessage();
                }

                LogUtil.showLog(LogConst.HTTP_TAG, errorMessage);
                onError(code, errorMessage);
                onComplete();
            }
        }
    }

    @SuppressLint("NewApi")
    @Override
    public void onComplete() {
        if (activity != null) {
            BaseActivity activity = this.activity.get();
            if (activity != null && !activity.isDestroyed()) {
                //请求结束
                if (isOpenLoading) {
                    activity.hideLading();
                }
                if (compositeDisposable != null) {
                    compositeDisposable.clear();
                }
            }
        }
    }
}